import re
import time

from pom.Admin.TrainingBankPage import AdminBankManage
from pom.base import BaseDriver

class TrainingBank(BaseDriver):

    def __init__(self, driver):
        super(TrainingBank, self).__init__(driver)
        self.tb = AdminBankManage(driver)

    """
    跳转到实训题库页面
    """
    def jump_train_bank(self):
        self.tb.Click(self.tb.bank_manage)
        self.tb.Click(self.tb.training_bank)

    def jump_competation_bank(self):
        self.Click(self.tb.bank_manage)
        self.Click(self.tb.competation_bank)

    def click_title(self, line):
        self.Click(self.tb.bank_list_data_ele(line, 2))


    """
    导入题库
    """
    def import_bank(self, file):
        self.Sendkeys(self.tb.import_btn, file)


    # 发布时间排序降序
    def sort_by_update_desc(self):
        self.Click(self.tb.update_time_desc_sort)

    def sort_by_update_asc(self):
        self.Click(self.tb.update_time_asc_sort)

    """
    根据发布时间排序降序
    """
    def sort_by_publish_desc(self):
        self.Click(self.tb.publish_time_desc_sort)

    def sort_by_publish_asc(self):
        self.Click(self.tb.publish_time_asc_sort)


    # 上一页

    def next_page(self):
        self.Click(self.tb.page_right)
        time.sleep(2)
        self.logger.info("点击下一页")
    # 下一页
    def front_page(self):
        self.Click(self.tb.page_left)
        time.sleep(1)
        self.logger.info("点击上一页")
    # 页面返回的所有数据条数（翻页左边）
    def total_num(self):
        num = self.tb.total_num.text
        s = re.findall("\d+", num)[0]
        self.logger.info("总数为：" + s)
        return s

    # 总共分页的数量
    def page_num(self):
        total_num = self.total_num()
        page_num = int(total_num) // int(10)
        if int(total_num) % 10 == 0:
            self.logger.info("总页数为：{}".format(page_num))
        else:
            self.logger.info("总页数为：{}".format(page_num+1))
        return page_num

    """
    新增题库
    """
    def create_bank(self, bankplate=None, title=None, desc=None, image=2, answerplate=None, otherdesc=None, file=None):
        """
        :param bankplate: 所属模块（1：初级、2：中级、3：高级)
        :param title:套题标题
        :param desc:简介
        :param image:镜像关联（1：是，2：否）
        :param answerplate:答题模式（1：简易模式，2:困难模式）
        :param otherdesc:其他说明
        :param file:上传附件
        :return:
        """
        self.tb.logger.info("---------创建题库----------")

        self.tb.Click(self.tb.add_bank_btn)
        try:
            self.tb.Click(self.tb.create_plate)
            if bankplate == 1:
                self.tb.Click(self.tb.create_primary)
            elif bankplate == 2:
                self.tb.Click(self.tb.create_mudeium)
            elif bankplate == 3:
                self.tb.Click(self.tb.create_senior)
            elif bankplate == None:
                pass
            else:
                self.tb.logger.error("创建题库-题库模块选择失败")
                raise Exception
        except Exception:
            pass

        self.tb.Sendkeys(self.tb.paper_title, title)
        self.tb.Sendkeys(self.tb.desc, desc)
        if image == 1:
            self.tb.Click(self.tb.connect_image)
        elif image == 2:
            self.tb.Click(self.tb.not_connect_image)
        else:
            self.tb.logger.error("创建题库-关联镜像失败")
            raise Exception
        try:
            self.tb.Click(self.tb.answer_model)
            if answerplate == 1:
                self.tb.Click(self.tb.easy_model)
            elif answerplate == 2:
                self.tb.Click(self.tb.hard_model)
            else:
                self.tb.logger.error("创建题库-答题模式失败")
                raise Exception
        except Exception:
            pass
        self.tb.Sendkeys(self.tb.other_desc, otherdesc)
        if file == None:
            pass
        else:
            self.tb.Sendkeys(self.tb.upload_file, file)
        self.Click(self.tb.confirm_btn)


    """
    根据 版块 过滤实训题库
    """
    def filter_by_plate(self, plate):
        """

        :param plate:初级、中级、高级、真题
        :return:
        """
        self.tb.Click(self.tb.plate)
        if plate == "初级":
            self.tb.Click(self.tb.primary)
        elif plate == "中级":
            self.tb.Click(self.tb.medium)
        elif plate == "高级":
            self.tb.Click(self.tb.senior)
        elif plate == "真题":
            self.tb.Click(self.tb.forCompa)
        else:
            self.tb.logger.error("实训题库 选择板块 错误")

    def filter_by_status(self, status):
        """
        根据题库状态筛选
        :param status: 已发布、未发布
        :return:
        """
        self.tb.Click(self.tb.status)
        if status == "已发布":
            self.tb.logger.info("选择【已发布】状态")
            self.tb.Click(self.tb.pulish)
        elif status == "未发布":
            self.tb.logger.info("选择【未发布】状态")
            self.tb.Click(self.tb.notPublish)
        else:
            self.tb.logger.error("选择实训题库状态失败")
            raise Exception


    def filter_by_title(self, filter_text):
        """
        根据标题筛选题库
        :param filter_text:关键字
        :return:
        """
        self.Clearandsend(self.tb.search_box, filter_text)
        self.Click(self.tb.search_btn)


    # 根据搜索结果筛选后的结果数量
    def search_result_num(self):
        lens = len(self.tb.search_result_list)
        self.tb.logger.info("搜索结果共{}条".format(lens))
        return lens

    # 列表中line行col列的数据
    def bank_list_data(self, line, col):
        text = self.tb.bank_list_data_ele(line, col).text
        bank_name = self.tb.bank_list_data_ele(line, 2).text
        self.tb.logger.info("[{}]题库该项数据为[{}]".format(bank_name, text))
        return text

    # 当标签为多个时
    def mul_bank_list_data(self, line, col):
        """
        返回第line行第col列的数据
        :param line: 行数   从1开始
        :param col: 列数  从1开始
        :return: 元素的text值
        """
        lens = len(self.tb.bank_list_data_num(line, col))
        if lens == 1:
            texts = self.tb.mul_bank_list_data_ele(line, col).text
        elif lens == 0:
            raise Exception
        else:
            texts = []
            for i in range(1, lens+1):
                texts.append(self.tb.mul_bank_list_data_ele(line, col, i).text)

        bank_name = self.tb.bank_list_data_ele(line,2).text
        self.tb.logger.info("[{}]题库该项数据为[{}]".format(bank_name, texts))
        return texts




    # 对不确定列表元素有几个时。检验搜索结果
    # 例如题库页面，板块信息 真题与初级高级同在时
    def mul_check_result(self, check_col, filter_text):
        """
        :param check_col: 需要检查的列数（从一开始）
        :param filter_text: 筛选内容（高级、初级、中级、真题、未发布、已发布、或者标题）
        :return:0 成功  -1 不成功
        """
        try:
            x = 1
            page_num = self.page_num()
        except Exception as e:
            print(e)
            x = 0
            page_num = 1
        for page in range(1, page_num + 2):
            # texts = self.mul_bank_list_data(1, check_col)
            lens = self.search_result_num()
            for i in range(1, lens + 1):
                num = len(self.tb.bank_list_data_num(i, check_col))
                if num == 1:
                    if self.mul_bank_list_data(i, check_col) == filter_text:
                        continue
                    else:
                        return -1
                else:
                    data = self.bank_list_data(i, check_col)
                    if data == filter_text or filter_text in data:
                        continue
                    else:
                        return -1
            if x == 0:
                pass
            else:
                self.next_page()
        else:
            self.tb.logger.info("筛选结果全部匹配")

            return 0

            # try:
                #     if self.mul_bank_list_data(i, check_col) == filter_text or filter_text in self.mul_bank_list_data(i, check_col):
                #         continue
                # except Exception:
                #     if self.bank_list_data(i, check_col) == filter_text or filter_text in self.bank_list_data(i,
                #                                                                                               check_col):
                #         continue
                # else:
                #     self.tb.logger.error("有数据与筛选项不符 请查看截图")
                #     return -1
    """降序排列检查结果"""
    def compare_desc_check_result(self, col):
        first = None
        for j in range(1, self.page_num() + 2):
            num = self.search_result_num()
            end = self.bank_list_data(num, col)
            if first == None or end == None or first >= end:
                pass
            else:
                return 1
            for i in range(1, num):
                if self.bank_list_data(i, col) >= self.bank_list_data(i + 1, col):
                    continue
                else:
                    return 1
            self.next_page()
            time.sleep(1)
            first = self.bank_list_data(1, col)
        return 0

    def compare_asc_check_result(self, col):
        first = None
        for j in range(1, self.page_num() + 2):
            num = self.search_result_num()
            end = self.bank_list_data(num, col)
            if first == None or first <= end:
                pass
            else:
                return 1
            for i in range(1, num):
                if self.bank_list_data(i, col) <= self.bank_list_data(i + 1, col):
                    continue
                else:
                    return 1
            self.next_page()
            time.sleep(1)
            first = self.bank_list_data(1, col)
        return 0


    def check_result(self, check_col, filter_text):
        try:
            x = 1
            page_num = self.page_num()
        except Exception as e:
            print(e)
            x = 0
            page_num = 1
        for page in range(1, page_num + 2):
            # texts = self.mul_bank_list_data(1, check_col)
            lens = self.search_result_num()
            for i in range(1, lens + 1):
                data = self.bank_list_data(i, check_col)
                if data == filter_text or filter_text in data:
                    continue
                else:
                    return -1
            if x == 0:
                pass
            else:
                self.next_page()
        else:
            self.tb.logger.info("筛选结果全部匹配")
            return 0



